package com.easy.cloud.web.component.security.interceptor;

import com.easy.cloud.web.component.core.tenant.TenantContextHolder;
import com.easy.cloud.web.component.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 传递 RestTemplate 请求的租户ID
 *
 * @author GR
 * @date 2021-4-7 10:19
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantContextHolderInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 租户ID从登陆信息中读取
            String tenant = SecurityUtils.getAuthenticationUser().getTenant();
            TenantContextHolder.setTenantId(tenant);
        } catch (Exception ignored) {
            log.info("TenantContextHolderFilter read tenant is null;");
        }

        return true;
    }
}
